const myAxios = function (config) {
  console.log(config);
  const {url,method,data,params } = config
  return new Promise((resolve, reject) => {
    // 原生Ajax请求
    const xhr = new XMLHttpRequest()
    // url固定值
    if (method === 'GET') {
      const str = setParams(params)
      xhr.open('GET', params ? url + `?` + str : url)
      xhr.send()
    } else { 
      xhr.open('POST', url)

      const flag = Object.prototype.toString.call(data) === '[object Object]'
      
      xhr.setRequestHeader('Content-Type', flag ? 'application/json' : 'application/x-www-form-urlencoded')
     
      xhr.send(flag ? JSON.stringify(data) : data)
    }
    

    // 监听
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(JSON.parse(xhr.responseText))
        } else { 
          reject('请求失败，请求状态' + xhr.status)
        }
       }
    }
  })
}

function setParams(obj) {
  const arr = []
  for (let key in obj) {
    const newArr = key + `=` + obj[key]
    arr.push(newArr)
    // console.log(arr);
  }
  return arr.join('&')
  
}
